﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.DbEntity.sys;
using Entity.FrameEntity;
using Entity.ViewEntity;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Tools;
using static System.Net.Mime.MediaTypeNames;

namespace SysFramework
{
    public class SystemManagement:PubMethod
    {
        ReturnResult rsl;
        Commands cmd;
        OperateModel oper;
        List<OperateModel> operList;
        

        public SystemManagement()
        {
            rsl = new ReturnResult();
            cmd = new Commands();
            oper = new OperateModel();
        }
    
        /// <summary>
        /// 系统登录方法(统一方法)
        /// </summary>
        /// <param name="userJson">json字符串</param>
        /// <returns></returns>
        public ReturnResult login(string userJson)
        {
            rsl = new ReturnResult();
            try
            {

                rsl=GetLicense("XR");
                if (!rsl.Result)
                {
                    return rsl;
                }

                if (string.IsNullOrWhiteSpace(userJson))
                {
                    rsl.Message = "参数丢失";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(userJson);
                if (json.Property("userCode") ==null || string.IsNullOrWhiteSpace(json["userCode"].ToString()))
                {
                    rsl.Message = "登录账号不允许为空";
                    return rsl;
                }
                if (json.Property("userPwd") == null || string.IsNullOrWhiteSpace(json["userPwd"].ToString()))
                {
                    rsl.Message = "登录密码不允许为空";
                    return rsl;
                }
                DbUser user = new DbUser();
                user.userCode = json["userCode"].ToString().Trim();
                user.userPwd = Tools.Encryption.MD5Encode(json["userPwd"].ToString().Trim());
                user.status = "Y";
                var list = cmd.GetDataByObject<LoginUser>(user);
                if (list.Count > 0)
                {
                    list[0].baseCode = json["baseCode"].ToString();
                    rsl.Data = list[0];

                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "账号或密码错误";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 导航信息菜单显示
        /// </summary>
        /// <param name="userCode">登录人账号</param>
        /// <param name="mType">菜单类型(PC/YD)</param>
        /// <returns></returns>
        public ReturnResult Navigation(string userCode,string mType = "")
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                #region 获取全部有效菜单信息
                sb.Append("select * from sys_MenuInfo ");
                sb.Append(" where status='Y' and isdel=0 ");
                if (string.IsNullOrWhiteSpace(mType))
                {
                    sb.Append(" and mType='PC'");
                }
                else
                {
                    sb.Append(" and mType='YD'");
                }
                var table = cmd.GetDataTable(sb.ToString());//获取全部有效菜单信息
                #endregion

                #region 获取用户菜单权限
                sb.Clear();
                sb.Append("select * from sys_powerConfig_groupPower where groupCode in(");
                sb.Append("select powerRole from sys_users_info where userCode='" + userCode + "')");
                #endregion
                var uMenus = cmd.GetDataTable(sb.ToString());//获取用户菜单权限
                DataTable sTable = new DataTable();
                sb.Clear();
                sb.Append("select top 1 isAdmin from sys_users_info where userCode='"+ userCode +"'");
                var uTable = cmd.GetDataTable(sb.ToString());
                #region
                if (uTable.Rows.Count<1 || uTable.Rows[0][0].ToString()=="0")
                {
                    #region  非管理员身份
                    sTable = table.Clone();
                    List<string> mlist = new List<string>();
                    foreach (DataRow r in uMenus.Rows)
                    {
                        var dr = table.Select("menuCode='" + r["menuCode"].ToString() + "'");//查询菜单是否有效
                        if (dr.Length > 0)
                        {
                            if (!mlist.Contains(r["menuCode"].ToString()))
                            {
                                sTable.Rows.Add(dr[0].ItemArray);
                                mlist.Add(r["menuCode"].ToString());
                                if (dr[0]["parentMenu"] != null && !string.IsNullOrWhiteSpace(dr[0]["parentMenu"].ToString()))
                                {
                                    UserMenuData(dr[0]["parentMenu"].ToString(), table, ref sTable, ref mlist);
                                }

                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    sTable = table;//管理员身份直接获取全部身份信息
                }
                #endregion
               rsl.Data = this.CreateNavigationList(sTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        #region 用户菜单权限
        /// <summary>
        /// 用户菜单权限
        /// </summary>
        /// <param name="pMenu">父级菜单编码</param>
        /// <param name="qtable">全部菜单</param>
        /// <param name="sTable">显示菜单</param>
        /// <param name="list">菜单编码集合</param>
        private void UserMenuData(string pMenu, DataTable qtable, ref DataTable sTable, ref List<string> list)
        {
            if (!string.IsNullOrWhiteSpace(pMenu))
            {
                if (!list.Contains(pMenu))
                {
                    var dr = qtable.Select("menuCode='" + pMenu + "'");
                    if (dr.Length > 0)
                    {
                        sTable.Rows.Add(dr[0].ItemArray);
                        list.Add(pMenu);
                        UserMenuData(dr[0]["parentMenu"].ToString(), qtable, ref sTable, ref list);
                    }
                }

            }
        }
        #endregion

        #region 创建导航数据
        /// <summary>
        /// 创建导航数据
        /// </summary>
        /// <param name="table">数据源</param>
        /// <returns></returns>
        private List<Dictionary<string, object>> CreateNavigationList(DataTable table)
        {
            List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
            #region 构建数据
            var fMenu = table.Select("menuLevel=1").OrderBy(x => x["orderNum"]).CopyToDataTable();//获取所有父级菜单
            for (int i = 0; i < fMenu.Rows.Count; i++)
            {
                var fdic = new Dictionary<string, object>();
                fdic["menuName"] = fMenu.Rows[i]["menuName"].ToString();
                fdic["menuIcon"] = fMenu.Rows[i]["menuIcon"].ToString();

                #region 子菜单
                List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                this.ChildUrl(table, fMenu.Rows[i]["menuCode"].ToString(), fMenu.Rows[i]["menuName"].ToString(), fMenu.Rows[i]["menuIcon"].ToString(), ref cList);
                fdic["child"] = cList;
                #endregion
                menuList.Add(fdic);
            }
            #endregion
            return menuList;
        }
        #endregion
        /// <summary>
        /// 子菜单生成方法(递归)
        /// </summary>
        /// <param name="table"></param>
        /// <param name="menuCode"></param>
        /// <param name="menuName"></param>
        /// <param name="icon"></param>
        /// <param name="chlist"></param>
        private void ChildUrl(DataTable table, string menuCode, string menuName, string icon, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentMenu='" + menuCode + "'");
            if (dr.Length > 0)
            {
                var cMenus = dr.OrderBy(x => x["orderNum"]).CopyToDataTable();
                for (int x = 0; x < cMenus.Rows.Count; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["menuName"] = cMenus.Rows[x]["menuName"].ToString();
                    cdic["menuIcon"] = cMenus.Rows[x]["menuIcon"].ToString();
                    if (cMenus.Rows[x]["onclick"] == null || string.IsNullOrWhiteSpace(cMenus.Rows[x]["onclick"].ToString()))
                    {
                        cdic["onclick"] = "";
                    }
                    else
                    {
                        cdic["onclick"] = cMenus.Rows[x]["onclick"].ToString();
                    }
                    string webUrl = "";
                    if (cMenus.Rows[x]["menuPath"].ToString().IndexOf("?") > -1)
                    { //菜单已经存在了参数
                        webUrl = cMenus.Rows[x]["menuPath"].ToString() + "&menuCode=" + cMenus.Rows[x]["menuCode"].ToString();
                    }
                    else
                    {
                        webUrl = cMenus.Rows[x]["menuPath"].ToString() + "?menuCode=" + cMenus.Rows[x]["menuCode"].ToString();
                    }
                    cdic["url"] = webUrl;
                    ChildUrl(table, cMenus.Rows[x]["menuCode"].ToString(), cMenus.Rows[x]["menuName"].ToString(), cMenus.Rows[x]["menuIcon"].ToString(), ref tempList);
                    cdic["child"] = tempList;
                    chlist.Add(cdic);

                }

            }
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <param name="userCode"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult getMenuList(string pageIndex, string pageSize, string condition,string userCode, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                string sv = AppSettingHelper.ReadAppSettings("IsDevelop");
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");
                if (sv != "1" )
                {
                    sb.Append(" and status='Y' ");
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "parentMenu")
                            {
                                sb.Append(" parentMenu= '" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }

                        }
                    }
                }
                rsl.Data = cmd.PageList("V_MenuInfo", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取顶级菜单数据
        /// </summary>
        /// <returns></returns>
        public ReturnResult GetTopMenu()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select menuCode,menuName from sys_MenuInfo where menuLevel='1'");
                sb.Append(" and isdel=0 and status='Y' and mType='PC'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取有效的菜单数据信息
        /// </summary>
        /// <param name="menuCode"></param>
        /// <returns></returns>
        public ReturnResult getEnableMenuInfo()
        {
            rsl = new ReturnResult();
            try
            {
                string sql = "select menuCode,menuName from sys_MenuInfo where status='Y' and isdel=0";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 客户关联账套数据
        /// </summary>
        /// <returns></returns>
        public ReturnResult CustomBaseInfo()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_CustomBaseInfo");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        } 

        /// <summary>
        /// 根据编码获取客户数据信息
        /// </summary>
        /// <param name="DbCode">数据编码</param>
        /// <param name="isAll">是否显示全部</param>
        /// <returns>编码为空返回全部</returns>
        public ReturnResult getCustomBaseByCode(string DbCode, bool isAll = false)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_CustomerBase_info ");
                sb.Append("where status='Y' ");
                if (!string.IsNullOrWhiteSpace(DbCode))
                {
                    sb.Append(" and DbCode='" + DbCode + "'");
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 客户账套数据保存
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SaveBaseData(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "保存参数丢失";
                    return rsl;
                }
                var data = JsonConvert.DeserializeObject<DbCustomBase>(datas);

                if (string.IsNullOrWhiteSpace(data.serverIp))
                {
                    rsl.Message = "IP地址不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(data.baseName))
                {
                    rsl.Message = "数据库账套不允许为空";
                    return rsl;
                }
                else
                {
                    var arr = data.baseName.Split('_');
                    data.DbCode = arr[1].Trim();
                }
                if (string.IsNullOrWhiteSpace(data.baseName))
                {
                    rsl.Message = "数据库名不允许为空";
                    return rsl;
                }
                string sql = "select * from sys_CustomerBase_info where DbCode='" + data.DbCode + "'";
                var table = cmd.GetDataTable(sql);
                if (data.Id == null || data.Id == 0)
                {
                    #region 添加操作
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = "编码已存在"; return rsl;
                    }
                    rsl = cmd.Add(data);
                    #endregion
                }
                else
                {
                    #region 编辑操作
                    if (data.Id != int.Parse(table.Rows[0]["Id"].ToString()))
                    {
                        rsl.Message = "编码已存在"; return rsl;
                    }
                    OperateModel op = new OperateModel();
                    op.Conditions = "Id";
                    op.Data = data;
                    op.Types = OperateModel.OperateType.Edit;
                    rsl = cmd.Edit(op);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除客户关联账套数据
        /// </summary>
        /// <returns></returns>
        public ReturnResult delCustomBaseById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                DbCustomBase customBase  = new DbCustomBase();
                customBase.Id = Convert.ToInt32(dataId);

                rsl = cmd.Del(customBase);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取系统字典数据方法
        /// </summary>
        /// <param name="types"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getDictionaryInfo(string types, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                string sql = "select code,name from sys_dictionaries_info where types='" + types + "' and status=1 ";
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    sql = sql + condition;
                }
                var t = cmd.GetDataTable(sql);
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(t);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

       
        /// <summary>
        /// 解密用户cookie
        /// </summary>
        /// <param name="cookieStr">加密cookie字符串</param>
        /// <returns></returns>
        public JObject CheckLoginCookie(string cookieStr)
        {
            rsl = new ReturnResult();
            try
            {
                cookieStr=Tools.Encryption.DesDecrypt(cookieStr);
                return JsonConvert.DeserializeObject<JObject>(cookieStr);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return null;
        }

        #region 获取客户数据账套默认编码
        /// <summary>
        /// 获取客户数据账套默认编码
        /// </summary>
        /// <returns></returns>
        public string getDefaultBaseCode()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select top 1 DbCode from sys_CustomerBase_info ");
            sb.Append("where isDefault='Y' order by id desc ");
            var table = cmd.GetDataTable(sb.ToString());
            if (table.Rows.Count > 0)
            {
                return table.Rows[0]["DbCode"].ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取客户U8数据库
        /// </summary>
        /// <returns></returns>
        public string getDefaultERPCode()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select top 1 baseName from sys_CustomerBase_info ");
            sb.Append("where isDefault='Y' order by id desc ");
            var table = cmd.GetDataTable(sb.ToString());
            if (table.Rows.Count > 0)
            {
                return table.Rows[0]["baseName"].ToString();
            }
            else
            {
                return "";
            }
        }
        #endregion

        /// <summary>
        /// 系统参数列表模型
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">页面信息数</param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getParametersList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.AppSettingHelper.ReadAppSettings("PageSize");
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");
                sb = CreateSelectCondition(sb, condition);

                var list = cmd.PageList("V_parameterInfo", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 系统参数参加
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SaveParameter(string datas,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "保存参数丢失";
                    return rsl;
                }
                var data = JsonConvert.DeserializeObject<DbParameter>(datas);
                if (string.IsNullOrWhiteSpace(data.partype))
                {
                    rsl.Message = "参数类型不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(data.parCode))
                {
                    rsl.Message = "参数编码不允许为空";
                    return rsl;
                }

                string sql = "select * from sys_parameters_info where parCode='" + data.parCode + "'";
                var table = cmd.GetDataTable(sql);
                if (data.id == null || data.id == 0)
                {
                    #region 添加操作
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = "编码已存在"; return rsl;
                    }
                    data.createtime = DateTime.Now.ToString();
                    data.createuser =userCode;
                    data.isDel = 0;
                    rsl = cmd.Add(data);
                    #endregion
                }
                else
                {
                    #region 编辑操作
                    if (table.Rows.Count > 0)
                    {
                        if (data.id != int.Parse(table.Rows[0]["id"].ToString()))
                        {
                            rsl.Message = "编码已存在"; return rsl;
                        }
                    }
                    OperateModel op = new OperateModel();
                    op.Conditions = "Id";
                    op.Data = data;
                    op.Types = OperateModel.OperateType.Edit;
                    rsl = cmd.Edit(op);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据参数编码获取参数列表
        /// </summary>
        /// <param name="parCode"></param>
        /// <param name="isAll"></param>
        /// <returns></returns>
        public ReturnResult getParameterByCode(string parCode, bool isAll = false)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(parCode))
                {
                    rsl.Message = "关键参数为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_parameters_info ");
                sb.Append("where parCode='" + parCode + "' ");
                if (isAll)
                {
                    sb.Append(" isDel=0");
                }
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "查无此参数";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 参数数据删除方法
        /// </summary>
        /// <param name="parCode"></param>
        /// <returns></returns>
        public ReturnResult DelParmeter(string parCode,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(parCode))
                {
                    rsl.Message = "参数编码获取失败";
                    return rsl;
                }
                DbParameter par = new DbParameter();
                par.parCode = parCode;
                par.isDel = 1;
                par.delTime = DateTime.Now.ToString();
                par.delUser = userCode;
                oper = new OperateModel();
                oper.Data = par;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "parCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 菜单数据添加
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SaveMenuInfo(string datas,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "保存参数丢失";
                    return rsl;
                }
                var obj = JsonConvert.DeserializeObject<JObject>(datas);
                var data = JsonConvert.DeserializeObject<DbMenuInfo>(datas);
                #region 防空验证
                if (string.IsNullOrWhiteSpace(data.menuCode))
                {
                    rsl.Message = "菜单编码不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(data.menuName))
                {
                    rsl.Message = "菜单名称不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(data.mType))
                {
                    rsl.Message = "菜单类型不允许为空";
                    return rsl;
                }
                #endregion
                string sql = "select top 1 * from sys_MenuInfo where menuCode='" + data.menuCode + "'";
                var table = cmd.GetDataTable(sql);
                if (data.id == null || data.id == 0)
                {
                    #region 添加操作
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = "菜单编码已存在"; return rsl;
                    }
                    data.createtime = DateTime.Now.ToString();
                    data.createuser = userCode;
                    data.status = "Y";
                    data.isdel = 0;
                    if (string.IsNullOrWhiteSpace(data.parentMenu))
                    {
                        data.menuLevel = "1";
                    }
                    else
                    {
                        data.menuLevel = "2";
                    }
                    rsl = cmd.Add(data);
                    #endregion
                }
                else
                {
                    #region 编辑操作
                    List<OperateModel> operlist = new List<OperateModel>();
                    if (table.Rows.Count > 0)
                    {
                        if (data.id != int.Parse(table.Rows[0]["id"].ToString()))
                        {
                            rsl.Message = "该菜单编码已存在"; 
                            return rsl;
                        }
                    }
                    if (string.IsNullOrWhiteSpace(data.parentMenu))
                    {
                        data.menuLevel = "1";
                    }
                    else
                    {
                        data.menuLevel = "2";
                    }
                    OperateModel op = new OperateModel();
                    op.Conditions = "Id";
                    op.Data = data;
                    op.Types = OperateModel.OperateType.Edit;
                    operlist.Add(op);
                    #endregion

                    #region 菜单编码发生改变 修改关联数据
                    if (obj["oldMenu"].ToString()!=data.menuCode)
                    {
                        #region  角色应用权限
                        sql = "select id,menuCode from sys_powerConfig_groupPower where menuCode='" + obj["oldMenu"].ToString() + "'";
                        var rpTable = cmd.GetDataTable(sql);
                        DbRolePowers rp;
                        foreach (DataRow r in rpTable.Rows)
                        {
                            rp = new DbRolePowers();
                            rp.menuCode = data.menuCode;
                            rp.id =int.Parse(r["id"].ToString());
                            op = new OperateModel();
                            op.Data = rp;
                            op.Types = OperateModel.OperateType.Edit;
                            op.Conditions = "id";
                            operlist.Add(op);
                        }
                        #endregion

                        #region 菜单权限
                        sql = "select id,menuCode from sys_PowerConfig_web where menuCode='"+ obj["oldMenu"].ToString() + "'";
                        var wpTable = cmd.GetDataTable(sql);
                        DbWebPower wp;
                        foreach (DataRow r in wpTable.Rows)
                        {
                            wp = new DbWebPower();
                            wp.menuCode = data.menuCode;
                            wp.id = int.Parse(r["id"].ToString());
                            op = new OperateModel();
                            op.Data = wp;
                            op.Types = OperateModel.OperateType.Edit;
                            op.Conditions = "id";
                            operlist.Add(op);
                        }
                        #endregion
                    }
                    #endregion

                    rsl = cmd.MoreUpdate(operlist);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 菜单删除
        /// </summary>
        /// <param name="menuCode"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelMenuInfo(string menuCode, string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                if (string.IsNullOrWhiteSpace(menuCode))
                {
                    rsl.Message = "菜单编码丢失";
                    return rsl;
                }
                DbMenuInfo menu = new DbMenuInfo();
                menu.menuCode = menuCode;
                menu.isdel = 1;
                menu.delMsg = string.Format("{0}({1})",userCode,getNow());
                oper = new OperateModel();
                oper.Data = menu;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "menuCode";
                operList.Add(oper);

                DbRolePowers rp = new DbRolePowers();
                rp.menuCode = menuCode;
                oper = new OperateModel();
                oper.Data = rp;
                oper.Types = OperateModel.OperateType.Delete;
                operList.Add(oper);

                DbWebPower wp = new DbWebPower();
                wp.menuCode = menuCode;
                oper = new OperateModel();
                oper.Types = OperateModel.OperateType.Delete;
                oper.Data = wp;
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
             
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取页面动态字段信息
        /// </summary>
        /// <param name="menuCode"></param>
        /// <returns></returns>
        public ReturnResult GetWebFields(string menuCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(menuCode))
                {
                    rsl.Message = "关键编码丢失";
                    return rsl;
                }
                sb.Append("select isnull(columns,'') columns from sys_TableCloumns_config ");
                sb.Append(" where tCode='" + menuCode + "' and isdel=0 ");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count < 1 || string.IsNullOrWhiteSpace(table.Rows[0][0].ToString()))
                {
                    rsl.Message = "数据不存在";
                    return rsl;
                }
                rsl.Data = table.Rows[0][0].ToString();
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
  
        /// <summary>
        /// 高级检索界面字段列表
        /// </summary>
        /// <param name="menuCode"></param>
        /// <returns></returns>
        public ReturnResult LoadQueryFieldsList(string menuCode)
        {
            rsl = new ReturnResult();
            try
            {
                var list=QueryFields(menuCode);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 加载页面高级检索字段
        /// </summary>
        /// <param name="menuCode">菜单界面</param>
        /// <returns></returns>
        public ReturnResult LoadQueryFields(string menuCode)
        {
            rsl = new ReturnResult();
            try
            {
                var list = QueryFields(menuCode);
                if (list.Count > 0)
                {
                    List<Dictionary<string, object>> dlist = new List<Dictionary<string, object>>();
                    for (int i = 1; i < i + 1; i++)
                    {
                        var qlist = list.Where(k => k["gCode"].ToString() == i.ToString());
                        if (qlist.Count() < 1)
                        {
                            break;
                        }
                        List<Dictionary<string, string>> clist = new List<Dictionary<string, string>>();
                        foreach (var dl in qlist)
                        {
                            clist.Add(dl);
                        }
                        var dic=new Dictionary<string,object>();
                        dic["gfields"] = clist;
                        dlist.Add(dic);
                    }
                    rsl.Data = dlist;
                    rsl.Result = true;
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 查询字段添加
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddQueField(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(datas);
                var list = QueryFields(obj["tCode"].ToString());
                bool isAdd = true;
                oper = new OperateModel();
                DbTableCloumns col=new DbTableCloumns();
                if (list.Count > 0)
                {
                    #region 存在数据
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i]["fieldCode"].ToString() == obj["fieldCode"])
                        {
                            list[i] = obj;
                            isAdd = false;
                            break;
                        }
                    }
                    if (isAdd)
                    {
                        list.Add(obj);
                    }
                    col.columns = JsonConvert.SerializeObject(list);
                    col.tCode = obj["tCode"].ToString();
                    oper.Data = col;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "tCode";
                    rsl = cmd.Edit(oper);
                    #endregion
                }
                else
                {
                    #region 不存在 直接进行添加
                    list.Add(obj);
                    col.isdel = 0;
                    col.columns = JsonConvert.SerializeObject(list);
                    col.tCode = obj["tCode"].ToString();
                    col.tcType = "listQuery";
                    col.memo = obj["tCode"].ToString()+"查询字段";
                    rsl = cmd.Add(col);
                    #endregion
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }
        /// <summary>
        /// 删除查询字段
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult DelQueField(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(datas);
                var list =this.QueryFields(obj["tCode"].ToString());
                oper = new OperateModel();
                DbTableCloumns col = new DbTableCloumns();
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i]["fieldCode"].ToString() == obj["fieldCode"])
                        {
                            list.RemoveAt(i);
                            break;
                        }
                    }
                    col.columns = JsonConvert.SerializeObject(list);
                    col.tCode = obj["tCode"].ToString();
                    oper.Data = col;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "tCode";
                    rsl = cmd.Edit(oper);
                }
               

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }
        /// <summary>
        /// 页面查询字段列表
        /// </summary>
        /// <param name="menuCode">菜单编码</param>
        /// <returns></returns>
        private List<Dictionary<string, string>> QueryFields(string menuCode)
        {
            StringBuilder sb = new StringBuilder();
            List<Dictionary<string, string>> dlist = new List<Dictionary<string, string>>();
            if (!string.IsNullOrWhiteSpace(menuCode))
            {
                sb.Append("select columns from sys_TableCloumns_config where isdel=0");
                sb.Append(" and tcType='listQuery' and tCode='"+menuCode+"'");
                var colTable = cmd.GetDataTable(sb.ToString());
                if (colTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(colTable.Rows[0][0].ToString()))
                {
                   dlist = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(colTable.Rows[0][0].ToString());
                }
                for (int i = 0; i < dlist.Count; i++)
                {
                    if (dlist[i]["fieldType"] == "fxlk" && !string.IsNullOrWhiteSpace(dlist[i]["dSoure"]))
                    {
                        sb.Clear();
                        var tTable = cmd.GetDataTable(dlist[i]["dSoure"]);
                        string dsoure = "";
                        foreach (DataRow r in tTable.Rows)
                        {
                            dsoure += string.Format("{0},{1};", r[0].ToString(), r[1].ToString());
                        }
                        dlist[i]["dSoure"] = dsoure.TrimEnd(';');
                    }
                }
            }
            return dlist;
        }

        /// <summary>
        /// 根据菜单编码获取菜单详细
        /// </summary>
        /// <param name="menuCode">菜单编码</param>
        /// <returns></returns>
        public ReturnResult getMenuByCode(string menuCode)
        {
            rsl = new ReturnResult();
            try
            {
                string sql = "select * from sys_MenuInfo where menuCode='" + menuCode + "'";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 数据同步保存方法
        /// </summary>
        /// <param name="list">数据源</param>
        /// <param name="syncTitle">数据标题</param>
        public void SubmitSyncData(List<OperateModel> list,string syncTitle,ref string msg)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(syncTitle))
                {
                    syncTitle = "未定义";
                }
                if (list.Count < 1000)
                {
                    rsl = cmd.MoreUpdate(list);
                }
                else
                {
                    var count = AppSettingHelper.ReadAppSettings("AutoTask", "SyncSize");//读取更新信息条数
                    int pcount = 0;
                    var page = list.Count / int.Parse(count);
                    if (list.Count % int.Parse(count) > 0)
                    {
                        pcount = page + 1;
                    }
                    for (int i = 0; i < pcount; i++)
                    {
                        var qList = list.Skip(i * int.Parse(count)).Take(int.Parse(count)).ToList();
                        rsl = cmd.MoreUpdate(qList);
                        
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
          
            }
        }
        /// <summary>
        /// 获取表格数据
        /// </summary>
        /// <param name="tCode"></param>
        /// <returns></returns>
        public ReturnResult GetTableCloums(string tCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(tCode))
                {
                    rsl.Message = "数据表编码丢失";
                    return rsl;
                }
                sb.Append("select * from sys_WebTableSet_main where webCode='" + tCode + "' and isdel=0");
                var mTable = cmd.GetDataTable(sb.ToString());
                sb.Clear();
                sb.Append("select * from sys_WebTableSet_sub where webCode='" + tCode + "' and isdel=0");
                sb.Append(" order by orderNum asc");
                var sTable = cmd.GetDataTable(sb.ToString());
                List<List<Dictionary<string, object>>> dlist = new List<List<Dictionary<string, object>>>();
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic;
                if (mTable.Rows.Count > 0)
                {
                    if (mTable.Rows[0]["moreCheck"].ToString() == "Y")
                    {
                        dic = new Dictionary<string, object>();
                        dic.Add("type", "checkbox");
                        dic.Add("fixed", "left");
                        list.Add(dic);
                    }
                    foreach (DataRow r in sTable.Rows)
                    {
                        dic = new Dictionary<string, object>();
                        dic.Add("field", r["field"].ToString());
                        dic.Add("title", r["title"].ToString());
                        dic.Add("width", int.Parse(r["width"].ToString()));
                        if (r["fixedInfo"] != null && !string.IsNullOrWhiteSpace(r["fixedInfo"].ToString()))
                        {
                            dic.Add("fixed", r["fixedInfo"].ToString());
                        }
                        list.Add(dic);
                    }
                    if (mTable.Rows[0]["isOperate"].ToString() == "Y")
                    {
                        dic = new Dictionary<string, object>();
                        dic.Add("field", "right");
                        dic.Add("align", "center");
                        dic.Add("title", "数据操作");
                        dic.Add("width", 100);
                        dic.Add("toolbar", "#barDemo");
                        dic.Add("fixed", "right");
                        list.Add(dic);
                    }
                    dlist.Add(list);
                }
                rsl.Data = dlist;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 上传文件方法
        /// </summary>
        /// <param name="businessType"></param>
        /// <param name="businessId"></param>
        /// <param name="files"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult UploadFile(string businessType,string businessId, IFormFileCollection files, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (files == null || files.Count <= 0)
                {
                    rsl.Message = "文件为空!"; return rsl;
                }
                string fileName = Path.GetFileName(files[0].FileName);
                string fileEx = System.IO.Path.GetExtension(fileName);//获取上传文件的扩展名
                string NoFileName = System.IO.Path.GetFileNameWithoutExtension(fileName);//获取无扩展名的文件名
                int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
                string newFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + NoFileName + fileEx;
                
                string path = Directory.GetCurrentDirectory() + "/wwwroot/upload";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);//根据路径创建指定文件
                }
                string savePath = Path.Combine(path, newFileName);
                using (var stream = System.IO.File.Create(savePath))
                {
                    //files[0].CopyToAsync(stream);
                    files[0].CopyTo(stream);
                }
                DbuploadFiles upFile = new DbuploadFiles();
                upFile.businessType = businessType;
                upFile.fileName = newFileName;
                upFile.businessID = businessId;
                upFile.filePath = "/upload/" + newFileName;
                //upFile.filePath = savePath;
                upFile.isDel = 0;
                upFile.createtime = getNow();
                upFile.createuser = userCode;
                rsl = cmd.Add(upFile);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }

        /// <summary>
        /// 获取图片附件
        /// </summary>
        /// <param name="tCode"></param>
        /// <returns></returns>
        public ReturnResult getUploadFiles( string businessId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(businessId))
                {
                    rsl.Message = "数据编码丢失";
                    return rsl;
                }
                sb.Append("select * from sys_upload_files where isdel='0' and businessId='" + businessId + "'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "数据不存在附件";
                    return rsl;
                }

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="tCode"></param>
        /// <returns></returns>
        public ReturnResult delUploadFiles(string id,string fileName)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    rsl.Message = "数据编码丢失";
                    return rsl;
                }

                string path = Directory.GetCurrentDirectory() + "/wwwroot/upload";
                string file = Path.Combine(path, fileName);

                DbuploadFiles upFile = new DbuploadFiles();
                upFile.id = Convert.ToInt32(id);

                rsl = cmd.Del(upFile);

                if (System.IO.File.Exists(file))
                {
                    System.IO.File.Delete(file);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 任务中心配置
        /// </summary>
        /// <param name="taskCode">任务编码</param>
        /// <param name="taskMemo">任务备注名称</param>
        /// <param name="timeValue">执行时间(为空时默认15分钟)</param>
        /// <returns></returns>
        public ReturnResult TaskSetInfo(string taskCode,string taskMemo,int timeValue=15)
        {
            rsl = new ReturnResult();
            try
            {
            
                StringBuilder sb = new StringBuilder();
                sb.Append("select isnull(timeValue,'') timeValue,isnull(doNextTime,'') doNextTime,id from sys_AutoTask_set ");
                sb.Append(" where taskCode='" + taskCode + "'and status='Y'");
                var table = cmd.GetDataTable(sb.ToString());
                DbAutoTaskSet ats;
                if (table.Rows.Count < 1)
                {
                    ats = new DbAutoTaskSet();
                    ats.taskCode = taskCode;
                    ats.timeValue = timeValue.ToString();
                    ats.doNextTime = DateTime.Now.AddMinutes(timeValue).ToString("yyyy-MM-dd HH:mm:ss");
                    ats.createtime = getNow();
                    ats.status = "Y";
                    ats.memo = taskMemo;
                    rsl = cmd.Add(ats);

                }
                else
                {
                    ats = new DbAutoTaskSet();
                    ats.id = int.Parse(table.Rows[0]["id"].ToString());
                    if (!string.IsNullOrWhiteSpace(table.Rows[0]["timeValue"].ToString()))
                    {
                        timeValue =int.Parse(table.Rows[0]["timeValue"].ToString());
                    }
                    if (!string.IsNullOrWhiteSpace(table.Rows[0]["doNextTime"].ToString()))
                    {
                        if (DateTime.Now < DateTime.Parse(table.Rows[0]["doNextTime"].ToString()))
                        {
                            rsl.Result = false;
                            rsl.Message = "时间未到，不执行";
                            return rsl;
                        }
                    }

                    ats.doNextTime = DateTime.Now.AddMinutes(timeValue).ToString("yyyy-MM-dd HH:mm:ss");
                    oper = new OperateModel();
                    oper.Data = ats;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    rsl = cmd.Edit(oper);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

    }



}
